package com.digitalchina.lxnsy.activity.old;

import android.content.pm.ActivityInfo;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.digitalchina.lxnsy.R;
import com.digitalchina.lxnsy.api.BusinessCollect;
import com.digitalchina.lxnsy.base.BaseActivity;
import com.digitalchina.lxnsy.constant.MSG;
import com.digitalchina.lxnsy.constant.URL;
import com.digitalchina.lxnsy.entity.CollectVO;
import com.digitalchina.lxnsy.entity.FarmingInfoListVO;
import com.digitalchina.lxnsy.entity.TrainingListVO;
import com.digitalchina.lxnsy.toolkit.FastJsonUtil;
import com.digitalchina.lxnsy.toolkit.Utils;
import com.digitalchina.lxnsy.widget.MediaController;
import com.pili.pldroid.player.AVOptions;
import com.pili.pldroid.player.PLMediaPlayer;
import com.pili.pldroid.player.widget.PLVideoTextureView;
import com.zzhoujay.richtext.RichText;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;


public class TechnologyTrainingVideoDetailNewActivity extends BaseActivity {


    @Bind(R.id.VideoView)
    PLVideoTextureView mVideoView;
    @Bind(R.id.LoadingView)
    LinearLayout mLoadingView;
    @Bind(R.id.img_fullscreen)
    ImageView imgFullscreen;
    //    private String mVideoPath = "rtmp://61.150.65.204:1935/vod/18204c65-b116-45b3-931e-4493bfce6aa1.mp4";
    private String mVideoPath = "";
    private static final int MESSAGE_ID_RECONNECTING = 0x01;
    private MediaController mMediaController;
    private Toast mToast = null;
    //    private String mVideoPath = null;
    private int mRotation = 0;
    private int mDisplayAspectRatio = PLVideoTextureView.ASPECT_RATIO_FIT_PARENT; //default
    private boolean mIsActivityPaused = true;
    private int mIsLiveStreaming = 0;
    private TrainingListVO trainingListVO;

    private CollectVO collectVO;

    @Override
    public void setLayout() {
        setTitle("技术大讲堂");
        setContentLayout(R.layout.activity_technology_training_video_detail_new);

        Drawable img = getResources().getDrawable(R.drawable.ic_v_collect);
        img.setBounds(0, 0, img.getMinimumWidth()/2, img.getMinimumHeight()/2);
        mTvRight.setCompoundDrawables(img, null, null, null);
        mTvRight.setText("收藏");
        mTvRight.setVisibility(View.VISIBLE);
        RichText.initCacheDir(this);
    }

    private void setOptions(int codecType) {
        AVOptions options = new AVOptions();
        options.setInteger(AVOptions.KEY_PREPARE_TIMEOUT, 10 * 1000);
        options.setInteger(AVOptions.KEY_GET_AV_FRAME_TIMEOUT, 10 * 1000);
        options.setInteger(AVOptions.KEY_PROBESIZE, 128 * 1024);
        options.setInteger(AVOptions.KEY_LIVE_STREAMING, mIsLiveStreaming);
        options.setInteger(AVOptions.KEY_MEDIACODEC, codecType);

        options.setInteger(AVOptions.KEY_START_ON_PREPARED, 0);
        mVideoView.setAVOptions(options);

    }

    @Override
    public void initMember() {

        if (getIntent().hasExtra("TrainingListVO")) {
            trainingListVO = (TrainingListVO) getIntent().getSerializableExtra("TrainingListVO");
            if ("1".equals(trainingListVO.getVideoFlag())) {//1-上传的视频2-视频链接
                mVideoPath = URL.SERVER + "hls/"+trainingListVO.getVideoInfo()+"/"+trainingListVO.getVideoInfo()+".m3u8";
            } else {
                mVideoPath = trainingListVO.getVideoLink() + "";
            }

        } else  if (getIntent().hasExtra("TrainingListVOSc")) {
            collectVO = (CollectVO) getIntent().getSerializableExtra("TrainingListVOSc");
            if ("1".equals(collectVO.getVideoFlag())) {//1-上传的视频2-视频链接
                mVideoPath = URL.SERVER + "hls/"+collectVO.getVideo()+"/"+collectVO.getVideo()+".m3u8";
            } else {
                mVideoPath = collectVO.getVideoLink() + "";
            }

        } else {
            mVideoPath = (String) getIntent().getSerializableExtra("path");
        }


        mVideoView.setBufferingIndicator(mLoadingView);
        mLoadingView.setVisibility(View.VISIBLE);

        setOptions(AVOptions.MEDIA_CODEC_AUTO);
        mMediaController = new MediaController(this, false, mIsLiveStreaming == 1);
        mVideoView.setMediaController(mMediaController);

        mVideoView.setOnCompletionListener(mOnCompletionListener);
        mVideoView.setOnErrorListener(mOnErrorListener);

        mVideoView.setVideoPath(mVideoPath);
        mVideoView.start();

    }

    @Override
    protected void onPause() {
        super.onPause();
        mToast = null;
        mVideoView.pause();
        mIsActivityPaused = true;
    }

    @Override
    protected void onResume() {
        super.onResume();
        mIsActivityPaused = false;
        mVideoView.start();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mVideoView != null) {
            mVideoView.stopPlayback();
            mVideoView = null;
        }
    }

    public void onClickRotate(View v) {
        mRotation = (mRotation + 180) % 360;
        mVideoView.setDisplayOrientation(mRotation);
    }

    public void onClickSwitchScreen(View v) {
        mVideoView.setDisplayAspectRatio(PLVideoTextureView.ASPECT_RATIO_PAVED_PARENT);
    }


    private PLMediaPlayer.OnErrorListener mOnErrorListener = new PLMediaPlayer.OnErrorListener() {
        @Override
        public boolean onError(PLMediaPlayer mp, int errorCode) {
            boolean isNeedReconnect = false;
            switch (errorCode) {
                case PLMediaPlayer.ERROR_CODE_INVALID_URI:
                    showToast("Invalid URL !");
                    break;
                case PLMediaPlayer.ERROR_CODE_404_NOT_FOUND:
                    showToast("404 resource not found !");
                    break;
                case PLMediaPlayer.ERROR_CODE_CONNECTION_REFUSED:
                    showToast("Connection refused !");
                    break;
                case PLMediaPlayer.ERROR_CODE_CONNECTION_TIMEOUT:
                    showToast("Connection timeout !");
                    isNeedReconnect = true;
                    break;
                case PLMediaPlayer.ERROR_CODE_EMPTY_PLAYLIST:
                    showToast("Empty playlist !");
                    break;
                case PLMediaPlayer.ERROR_CODE_STREAM_DISCONNECTED:
                    showToast("Stream disconnected !");
                    isNeedReconnect = true;
                    break;
                case PLMediaPlayer.ERROR_CODE_IO_ERROR:
                    showToast("Network IO Error !");
                    isNeedReconnect = true;
                    break;
                case PLMediaPlayer.ERROR_CODE_UNAUTHORIZED:
                    showToast("Unauthorized Error !");
                    break;
                case PLMediaPlayer.ERROR_CODE_PREPARE_TIMEOUT:
                    showToast("Prepare timeout !");
                    isNeedReconnect = true;
                    break;
                case PLMediaPlayer.ERROR_CODE_READ_FRAME_TIMEOUT:
                    showToast("Read frame timeout !");
                    isNeedReconnect = true;
                    break;
                case PLMediaPlayer.ERROR_CODE_HW_DECODE_FAILURE:
                    setOptions(AVOptions.MEDIA_CODEC_SW_DECODE);
                    isNeedReconnect = true;
                    break;
                case PLMediaPlayer.MEDIA_ERROR_UNKNOWN:
                    break;
                default:
                    showToast("unknown error !");
                    break;
            }
            // Todo pls handle the error status here, reconnect or call finish()
            if (isNeedReconnect) {
                sendReconnectMessage();
            } else {
                showToast("视频播放失败，请检查是否为正常视频链接");
            }
            // Return true means the error has been handled
            // If return false, then `onCompletion` will be called
            return true;
        }
    };

    private PLMediaPlayer.OnCompletionListener mOnCompletionListener = new PLMediaPlayer.OnCompletionListener() {
        @Override
        public void onCompletion(PLMediaPlayer plMediaPlayer) {
            showToast("播放完成!");
            finish();
        }
    };


    @Override
    public void addListener() {

    }

    @Override
    public void setHandler() {
        mHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);

                switch (msg.what) {
                    case MSG.MSG_ADD_STORE_SUCCESS:
                        showToast("收藏成功");
                        break;

                    case MSG.MSG_ADD_STORE_FIELD:
                        showToast(msg.obj.toString());
                        break;
                }

            }
        };
    }

    @Override
    public void callBack(Object object) {

    }

    @Override
    public void rightOnClick() {
        if (trainingListVO == null)
            return;

        if (noLoginToSkip()){
            BusinessCollect.addStore(this, trainingListVO.id, "1", mHandler);
        }
    }


    private void sendReconnectMessage() {
        if (isFinishing() || mLoadingView == null)
            return;
        showToast("正在重连...");
        mLoadingView.setVisibility(View.VISIBLE);
        mHandler.removeCallbacksAndMessages(null);
        mHandler.sendMessageDelayed(mHandler.obtainMessage(MESSAGE_ID_RECONNECTING), 500);
    }

    protected Handler mHandler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what != MESSAGE_ID_RECONNECTING) {
                return;
            }
            if (mIsActivityPaused) {
                finish();
                return;
            }
            if (!Utils.isNetworkAvailable(TechnologyTrainingVideoDetailNewActivity.this)) {
                sendReconnectMessage();
                return;
            }
            mVideoView.setVideoPath(mVideoPath);
            mVideoView.start();
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @OnClick(R.id.img_fullscreen)
    public void onViewClicked() {

        if (mViewGroupActionBar.getVisibility() == View.VISIBLE) {
            mViewGroupActionBar.setVisibility(View.GONE);
            mVideoView.setDisplayAspectRatio(PLVideoTextureView.ASPECT_RATIO_PAVED_PARENT);
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
            imgFullscreen.setImageResource(R.drawable.icon_fullscreen_shrink);
            full(true);
        } else {
            mViewGroupActionBar.setVisibility(View.VISIBLE);
            mVideoView.setDisplayAspectRatio(PLVideoTextureView.ASPECT_RATIO_FIT_PARENT);
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
            imgFullscreen.setImageResource(R.drawable.icon_fullscreen_stretch);
            full(false);
        }
    }

    private void full(boolean enable) {
        if (enable) {
            WindowManager.LayoutParams lp = getWindow().getAttributes();
            lp.flags |= WindowManager.LayoutParams.FLAG_FULLSCREEN;
            getWindow().setAttributes(lp);
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
        } else {
            WindowManager.LayoutParams attr = getWindow().getAttributes();
            attr.flags &= (~WindowManager.LayoutParams.FLAG_FULLSCREEN);
            getWindow().setAttributes(attr);
            getWindow().clearFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
        }
    }
}